package cn.gson.crm.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.gson.crm.model.dao.PaymentPlanDAO;
import cn.gson.crm.model.dao.purchaseTbDAO;
import cn.gson.crm.model.pojo.Paymentplan;
import cn.gson.crm.model.pojo.PurchaseTb;
import cn.gson.crm.model.vo.PaymentPlanVO;

@Service
@Transactional
public class PpService {
	@Autowired
	private PaymentPlanDAO pdDao;
	@Autowired
	private purchaseTbDAO pTbDAO;
	
	public List<PaymentPlanVO> getAllpp(int page, int rows) {
		PageRequest pRequest = new PageRequest(page - 1, rows);
		List<Paymentplan> listpo = pdDao.getAllPP(pRequest);
		List<PaymentPlanVO> listvo = new ArrayList<>();
		for (Paymentplan p : listpo) {
			listvo.add(returnPPvo(p));
		}
		return listvo;
	}

	public PaymentPlanVO returnPPvo(Paymentplan p) {
		PaymentPlanVO pVo = new PaymentPlanVO(p.getPpId(), p.getPpCaiId(), p.getPpCaiName(), p.getPpCusId(),
				p.getPpCusName(), p.getPpMan(), p.getPpMoney(), p.getPpPeriod(), p.getPpState(), p.getPpTime());
		return pVo;
	}
	
	public Long count() {
		return pdDao.count();
	}
	
	public void deletepp(Long id) {
		try {
			pdDao.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 添加付款计划
	 * @param p
	 */
	public void addPaymentPlan(Paymentplan p) {
		PurchaseTb pTb = pTbDAO.findOne(p.getPpCaiId().longValue());
		if (pTb!=null) {
			p.setPurchaseTb(pTb);
		}
		pdDao.save(p);
	}
	
	public PaymentPlanVO getPpById(Long id) {
		return returnPPvo(pdDao.findOne(id));
	}
}
